package org.darcy.service.check.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.darcy.dao.CheckPlanMapper;
import org.darcy.entity.CheckPlan;
import org.darcy.entity.CheckPlanDetail;
import org.darcy.entity.business.BusinessFinancialReceived;
import org.darcy.entity.work.WorkInstance;
import org.darcy.framework.constant.SysConstant;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.framework.model.PageData;
import org.darcy.framework.model.PageParam;
import org.darcy.service.check.CheckPlanDetailService;
import org.darcy.service.check.CheckPlanService;
import org.darcy.service.work.WorkService;
import org.darcy.utils.UserTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

/**
 * CheckPlan服务实现
 */
@Service
@Transactional
public class CheckPlanServiceImpl extends GenericServiceImpl<CheckPlan> implements CheckPlanService {

	@Autowired
	private CheckPlanMapper mapper;

	@Autowired
	private CheckPlanDetailService CheckPlanDetailService;

	@Autowired
	private WorkService WorkService;

	@Override
	public CheckPlan getDetail(Integer id) {
		CheckPlan record = mapper.selectById(id);
		record.setTotalFee(record.getCheckFee() + record.getOtherFee());
		record.setDetailList(CheckPlanDetailService.getList(id));
		return record;
	}
	
	@Override
	public int delete(Object id) {
		super.delete(id);
		WorkInstance param = WorkInstance.builder().formId((Integer) id).formType(SysConstant.FormType.CheckPlan)
				.build();
		WorkInstance work = WorkService.getBusinessWork(param);
		WorkService.delete(work.getId());
		return 1;
	}

	/**
	 * 处理工作任务
	 */
	private void processWork(CheckPlan record) {
		String title = String.format("[%s]的%s", UserTool.getLoginUser().getRealName(), "采样计划");
		String time = DateUtil.format(record.getCreateTime(), "yyyy-MM-dd");
		String summary = String.format("采样时间：%s", time);
		WorkService.addWorkTask(record, title, summary, SysConstant.FormType.CheckPlan);
	}

	@Override
	public CheckPlan insert(CheckPlan record) {
		record.setCreateTime(new Date());
		// 编号处理
		String time = DateUtil.format(record.getCreateTime(), DatePattern.PURE_DATETIME_FORMATTER);
		record.setFormNo("CYJH" + time);
		super.insert(record);
		List<CheckPlanDetail> detailList = record.getDetailList();
		if (detailList != null) {
			for (CheckPlanDetail detail : detailList) {
				detail.setPlanId(record.getId());
				CheckPlanDetailService.insert(detail);
			}
		}
		processWork(record);
		return record;
	}

	@Override
	public CheckPlan update(CheckPlan record) {
		// 检测费用合计
		List<CheckPlanDetail> detailList = record.getDetailList();
		// 按检测类别、点位分组取最高采样价格
		Map<String, Float> maxPriceMap = new HashMap<String, Float>();
		for (CheckPlanDetail a : detailList) {
			String key = a.getCheckType() + a.getCheckSpot();
			Float thisPrice = a.getCollectPrice() == null ? 0f : a.getCollectPrice();
			Float maxPrice = maxPriceMap.get(key);
			if (maxPrice == null) {
				maxPriceMap.put(key, thisPrice);
			} else {
				if (maxPrice < thisPrice) {
					maxPriceMap.put(key, thisPrice);
				}
			}
		}

		float total = 0f;
		for (CheckPlanDetail a : detailList) {
			int count = a.getCheckFreq() * a.getCheckCycle() * a.getCheckSpotCount();
			total += (a.getCheckPrice() == null ? 0f : a.getCheckPrice()) * count;
			String key = a.getCheckType() + a.getCheckSpot();
			Float thisPrice = a.getCollectPrice() == null ? 0f : a.getCollectPrice();
			Float maxPrice = maxPriceMap.get(key);
			if (thisPrice < maxPrice) {
				continue;
			}
			total += (a.getCollectPrice() == null ? 0f : a.getCollectPrice()) * count;
		}
		record.setCheckFee(total);
		super.update(record);
		processWork(record);
		return record;
	}

	@Override
	public PageData<CheckPlan> page(PageParam<CheckPlan> param) {
		IPage<CheckPlan> queryPage = new Page<CheckPlan>(param.getQuery().getPageNum(), param.getQuery().getPageSize());
		IPage<CheckPlan> data = mapper.getPage(queryPage, param.getEntity());
		for (CheckPlan a : data.getRecords()) {
			if (a.getWork() != null)
				a.getWork().setStatusName(a.getWork().fetchStatusName());
		}
		PageData<CheckPlan> pageData = new PageData<CheckPlan>(data, param);
		return pageData;
	}

	@Override
	public List<CheckPlan> getAll(Integer clientId) {
		QueryWrapper<CheckPlan> q = new QueryWrapper<CheckPlan>();
		q.eq("client_id", clientId);
		List<CheckPlan> list = this.getList(q);
		for (CheckPlan a : list) {
			String time = DateUtil.format(a.getCreateTime(), DatePattern.PURE_DATE_FORMATTER);
			a.setDetail("编号：" + a.getFormNo() + ", 委托业务：" + a.getProjectType() + ", 提交时间：" + time);
		}
		return list;
	}

}
